var app = getApp();
var cms50k = require('../../../../utils/cms50k.js');
function buf2hex(buffer) {
	return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('')
};
function querySingleDataCapacity(datatype) {
  var buffer = new Array(3);

  buffer[0] = 0x90;
  buffer[1] = datatype;
  buffer[2] = cmsGetCheckSum(buffer);

  return buffer;
}
function cmsGetCheckSum(buffer) {
  var sum = 0;
  for (var i = 0; i < buffer.length - 1; ++i) {
    sum += buffer[i];
  }
  return (sum & 0x7F);
}
Page({
	data: {
		nonceId_arr: [],
		inputText: 'Hello World!',
		receiveText: '',
		name: '',
		j_id: "",
		status: '未连接',
    connected: false,
		connectedDeviceId: '',
		services: {},
		characteristics: {},
		connected: true,
		//		判断是否主动断开
		activeClose: false,
		serviceId: '',
		notifyCharacteristicsId: '',
		writeCharacteristicsId: '',
		pakInfoList: [],
		scorollTop: 100
	},
	onLoad: function (options) {
		this.BleInitial(options);
		//	  屏幕保存常亮
		wx.setKeepScreenOn({
			keepScreenOn: true
		})
	},
	onReady: function () {

	},
	onShow: function () {
	},
	onHide: function () {
		this.closeBleFun();
	},
	pakInfoFun(Text, data) {
		let paL = this.data.pakInfoList
		let inf
		inf = Text + data;
		let sT = this.data.scorollTop + 50;
		paL.push(inf)
		this.setData({
			pakInfoList: paL,
			scorollTop: sT
		})
	},
	//	断开连接
	closeBleFun() {
		let that = this;
		wx.closeBLEConnection({
			deviceId: this.data.connectedDeviceId,
			success: function () {
				console.log('close sucess')
				that.setData({
					activeClose: true
				})
			}
		})
	},
	//	返回
	baclkFun() {
		this.closeBleFun();
		wx.redirectTo({
			url: '/hyb_yl/zhuanjiasubpages/pages/danganList/danganList?j_id=' + this.data.j_id + '&doc=0&type=1'
		})
	},
	BlelinkFail() {
		let that = this;
		setTimeout(function () {
			//			判断,如果不是主动断开连接,则提示弹框
			if (!that.data.activeClose) {
				wx.showModal({
					title: '提示',
					showCancel: false,
					content: '蓝牙已断开连接，是否前往查看数据？',
					success(res) {
						if (res.confirm) {
							wx.redirectTo({
								url: '/hyb_yl/pharmacy/pages/temperature/temperature?j_id=' + that.data.j_id
							})
						}
					}
				})
			}
		}, 500)
	},
	//	设备蓝牙匹配，发送数据包
	BleInitial(options) {
		var that = this
		that.setData({
			name: options.name,
			connectedDeviceId: options.connectedDeviceId,
			deviceId: options.connectedDeviceId,
			j_id: options.j_id,
			type: options.type
		})
		if(options.type == 'tem')
		{
			wx.setNavigationBarTitle({
				title: '温度测量',
			})
		}else if(that.data.name.indexOf('PM') > -1){
			wx.setNavigationBarTitle({
				title: '心率测量',
			})
		}else{
			wx.setNavigationBarTitle({
				title: '胆固醇血糖血压',
			})
		}
		var buffer = new Array();
    var spo2_array = new Array();
    that.setData({
      dataBuffer: buffer,
      spo2_data: spo2_array
    });
		console.log(options)
		if (options.type == 'tem') {
			//获取蓝牙设备所有服务
			wx.getBLEDeviceServices({
				deviceId: that.data.connectedDeviceId,
				success: function (res) {
					let seAr = res.services
					seAr.forEach(v => {
						if (v.uuid.indexOf("00001000") > -1 || v.uuid.indexOf('0000FFB0') > -1) {
							that.setData({
								serviceId: v.uuid
							})
						}
					})

					//      获取蓝牙某个服务中的所有特征值
					wx.getBLEDeviceCharacteristics({
						deviceId: options.connectedDeviceId,
						serviceId: that.data.serviceId,
						success: function (res) {
							console.log('对应服务的特征值')
							console.log(res.characteristics)
							//              	 获取到的特征值有多个，最后要用的事能读，能写，能监听的那个值的uuid作为特征值
							let chaArr = res.characteristics
							res.characteristics.forEach(v => {
								if (v.uuid.indexOf("00001002") > -1 || v.uuid.indexOf('0000FFB2') > -1) {
									that.setData({
										notifyCharacteristicsId: v.uuid
									})
								}
								if (v.uuid.indexOf("00001001") > -1 || v.uuid.indexOf('0000FFB1') > -1) {
									that.setData({
										writeCharacteristicsId: v.uuid
									})
								}
							})
							that.pakInfoFun('设备信息serviceId：', that.data.serviceId)
							that.pakInfoFun('设备信息notifyCharacteristicsId：', that.data.notifyCharacteristicsId)
							that.pakInfoFun('设备信息writeCharacteristicsId：', that.data.writeCharacteristicsId)
							console.log(that.data.serviceId)
							console.log(that.data.notifyCharacteristicsId)
							console.log(that.data.writeCharacteristicsId)
							//启用低功耗蓝牙设备特征值变化时的 notify 功能，订阅特征值。
							//注意：必须设备的特征值支持 notify 或者 indicate 才可以成功调用。
							wx.notifyBLECharacteristicValueChange({
								state: true,
								deviceId: options.connectedDeviceId,
								serviceId: that.data.serviceId,
								characteristicId: that.data.notifyCharacteristicsId,
								success: function (res) {
									//发送'00'包,获取设备信息
									that.Send('00');
									console.log('开始发包')
								},
								fail: function (res) {
									console.log(res)
									console.log('开始发包失败')
								}
							})
						}
					})
				},
				fail: function (res) {
					console.log(res)
				}

			})
			//		监听蓝牙状态:包括连接异常/断开连接
			wx.onBLEConnectionStateChange(function (res) {
				console.log(res.connected)
				that.setData({
					connected: res.connected
				})
				if (!res.connected) {
					that.BlelinkFail();
				}
			})
			//		监听低功耗蓝牙设备的特征值变化事件
			wx.onBLECharacteristicValueChange(function (res) {
				//			var that = this;
				console.log('接收数据');
				console.log(res);
				var receiveText = buf2hex(res.value);
				console.log('接收到数据：' + receiveText);
				console.log(receiveText.length);
				that.pakInfoFun('接收数据：', receiveText)
				if (receiveText.length == 36) {
					//				'03':读取血糖数据
					that.Send('03');
				}
				if (receiveText.length == 24) {
					//处理测量结果
					var receiveTexts = that.handleResult(receiveText)
					receiveText = that.handleResult(receiveText) + '℃';
					that.setData({
						receiveText: receiveText
					});
					app.util.request({
						'url': "entry/wxapp/index.add_temperature",
						data: {
							openid: wx.getStorageSync('openid'),
							sn: that.data.serviceId,
							j_id: that.data.j_id,
							value: receiveTexts,
						},
						success: function (res) {

						}
					})
				}
			})
		} else {
			if(that.data.name.indexOf('PM') > -1)
			{
				wx.setStorageSync('j_id', that.data.j_id)
				this.connectThisDevice();
			}else{
				wx.createBLEConnection({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: that.data.connectedDeviceId,//设备id
					success: function (res) {
						wx.showToast({
							title: '连接成功',
							icon: 'fails',
							duration: 800
						})
						console.log(res)
						console.log("连接蓝牙成功!")
						wx.stopBluetoothDevicesDiscovery({
							success: function (res) {
								console.log('连接蓝牙成功之后关闭蓝牙搜索');
							}
						})
						that.getServiceId()//5.0
					}
				})
			}
			
		}


	},
	connectThisDevice: function() {
    var that = this;

    cms50k.connect({
      deviceId: that.data.deviceId,
      success: function(res) {
        that.setData({
          connected: true,
          status: "已连接",
        })

        cms50k.setTime({
          success: that.send_success,
          fail: that.send_fail,
          op_success: function() {
            that.setData({
              status: "对时成功",
            })
            that.getSingleECG();
          },
          op_fail: function() {
            that.setData({
              status: "对时失败",
            })
          }
        })
      },
      fail: function() {
        that.setData({
          connected: false,
          status: "连接失败, 1秒后重试",
        })

        setTimeout(function() {
          that.connectThisDevice();
        }, 1000);
      }
    })
	},
	send_success: function(res) {
    var that = this;
    that.setData({
      status: "发送指令成功",
    })
  },
  send_fail: function(res) {
    var that = this;
    that.setData({
      status: "发送指令失败",
    })
  },

  getSingleECG: function() {
    var that = this;

    that.setData({
      status: "获取心电数据中",
    })

    cms50k.getSingleECG({
      success: that.send_success,
      fail: that.send_fail,
      op_success: function(res) {
				console.log(res);
				console.log('获取心电数据成功');
        that.setData({
          status: "获取心电数据成功",
          ecg_cases: res.count, 
          ecg_data_precent:'接收完成',
          ecg_data: (res.count > 0) ? res.data : null
        })
      },
      op_fail: function(res) {
        that.setData({
          status: "获取心电数据失败",
        })
      },
      op_process: function (res) {
        var str = res.case_current.toString() + '/' + res.case_total.toString()
        var str1 = (Math.floor(res.data_current * 100 / res.data_total)).toString() + '%'
        that.setData({
          ecg_cases: str,
          ecg_data_precent: '进度' + str1
        })
      }
    })
  },

  send_success: function(res) {
    var that = this;
    that.setData({
      //    status: "发送指令成功",
    })
  },
  send_fail: function(res) {
    var that = this;
    that.setData({
      status: "发送指令失败",
    })
  },

  buf2hex: function(buffer) { // buffer is an ArrayBuffer
    return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join(' ');
  },

  viewECG: function(e) {
    var that = this;
    var id = e.currentTarget.id
    if ((that.data.ecg_data.length > 0) && (id < that.data.ecg_data.length)) {
      try {
        wx.setStorageSync('reviewECG', JSON.stringify(that.data.ecg_data[id]))
      } catch (e) {
        console.log(e)
        return
      }

      
      return;
    }
  },
	getServiceId() {
		var that = this
		wx.getBLEDeviceServices({
			// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
			deviceId: that.data.deviceId,
			success: function (res) {
				console.log(res)
				console.log(that.data.name)
				if (that.data.name.indexOf('PM') > -1) {
					for (var i = 0; i < res.services.length; ++i) {
						if (res.services[i].uuid.indexOf('FF12') >= 0) {
							var notifyServiceId = res.services[i].uuid;
							var writeServiceId = res.services[i].uuid;
							that.setData({
								notifyServiceId: notifyServiceId,
								writeServiceId: writeServiceId,
								services: res.services[i].uuid
							})

							that.getCharacteId()//6.0
							return;
						}
					}
				} else {
					if (that.data.name.indexOf('Device') > -1) {
						var model = res.services[1]
					} else {
						var model = res.services[0]
					}
					console.log(model);
					that.setData({
						services: model.uuid
					})
					that.getCharacteId()//6.0
				}
			}
		})
	},
	getCharacteId() {
		var that = this
		console.log(that.data.services)
		wx.getBLEDeviceCharacteristics({
			// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
			deviceId: that.data.deviceId,
			// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
			serviceId: that.data.services,
			success: function (res) {
				console.log(res)
				for (var i = 0; i < res.characteristics.length; i++) {//2个值
					var model = res.characteristics[i]
					if (that.data.name.indexOf('PM') > -1 && res.characteristics[i].properties.notify && res.characteristics[i].uuid.indexOf('FF02') >= 0) {
						that.startNotice(model.uuid)//7.0
					}
					if (model.properties.notify == true) {
						that.setData({
							notifyId: model.uuid//监听的值
						})
						that.startNotice(model.uuid)//7.0
					}
					if (model.properties.write == true) {
						that.setData({
							writeId: model.uuid//用来写入的值
						})
						// that.startNotice(model.uuid)//7.0
					}
				}
			}
		})
	},
	startNotice(uuid) {
		var that = this;

		wx.notifyBLECharacteristicValueChange({
			state: true, // 启用 notify 功能
			// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
			deviceId: that.data.deviceId,
			// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
			serviceId: that.data.services,
			// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
			characteristicId: uuid,  //第一步 开启监听 notityid  第二步发送指令 write
			success: function (res) {
				console.log(res)
				// 设备返回的方法
				console.log(res)
				console.log(that.data.name)
				console.log(that.data.writeServiceId);
				// 设备返回的方法
				if (that.data.name.indexOf('PM') > -1) {
					wx.getBLEDeviceCharacteristics({
						deviceId: that.data.deviceId,
						serviceId: that.data.writeServiceId,
						success: function (res) {
							for (var i = 0; i < res.characteristics.length; i++) {
								if ((res.characteristics[i].properties.write) && (res.characteristics[i].uuid.indexOf('FF01') >= 0)) {
									var writeCharacteristicId = res.characteristics[i].uuid;
									console.log(1111)
									var dataBuffer = new Array();
									const QUERY_SINGLE_DATA_CAPACITY_ECG = 3;
									querySingleDataCapacity(QUERY_SINGLE_DATA_CAPACITY_ECG), {
										success: function(res){
											console.log(res)
											var arr = res
											var buf = new ArrayBuffer(arr.length)
											var dataView = new DataView(buf)
										
											for (var i = 0; i < arr.length; i++) {
												dataView.setInt8(i, arr[i]);
											}
										
											wx.writeBLECharacteristicValue({
												deviceId: that.data.deviceId,
												serviceId: that.data.writeServiceId,
												characteristicId: writeCharacteristicId,
												value: buf,
												success: function(res){
													console.log(res)
												},
												fail: function(res){
													console.log(res)
												}
											})
										}
										
									}
									wx.onBLECharacteristicValueChange(function (res) {
										console.log(res)
									});

									return;
								}
							}
						},
						fail: function (res) {
							console.log(res)
						}
					})
				} else {
					wx.onBLECharacteristicValueChange(function (res) {
						console.log(res)
						var nonceId = buf2hex(res.value)
						//拿到这个值后，肯定要去后台请求服务（当前步骤根据当前需求自己书写），获取下一步操作指令写入到蓝牙设备上去
						console.log(nonceId)
						if (nonceId_arr.indexOf(nonceId) == -1) {
							that.data.nonceId_arr.concat(nonceId);
							if (that.data.nonceId_arr.length == 3) {
								var shuju = that.data.nonceId_arr[1];
								var status = 0; //测量状态
								var datas = 0;//测量值
								if (shuju == 'a5a5a5a5a5a5a5a5a5a5a5a500') {
									status = 2;
									that.setData({
										receiveText:'过高'
									})
								} else if (shuju == '5a5a5a5a5a5a5a5a5a5a5a5a00') {
									status = 1;
									that.setData({
										receiveText:'过低'
									})
								} else {
									var shuju1s = shuju.substr(4, 2);
									shuju1s = "0x" + shuju1s;
									shuju1s = parseInt(shuju1s, 16);
									var shuju2s = shuju.substr(2, 2);
									shuju2s = "0x" + shuju2s;
									shuju2s = shuju1s & shuju2s << 8;
									datas = shuju2s + shuju1s;
									if (that.data.type == 'GLU') {
										datas = datas / 10;
									} else if (that.data.type == 'UA') {
										datas = datas / 100;
									} else if (that.data.type == 'CHOL') {
										datas = datas;
									}
									that.setData({
										receiveText:datas
									})
									app.util.request({
										'url': "entry/wxapp/index.add_shebei",
										data: {
											openid: wx.getStorageSync('openid'),
											sn: that.data.serviceId,
											j_id: that.data.j_id,
											value: datas,
											status: status,
											type: that.data.type
										},
										success: function (res) {
											wx.showModal({
												title: '提示',
												content: "测量成功",
												showCancel: false,
												success: function (con) {
													if (that.data.type == 'GLU') {
														wx.navigateTo({
															url: '/hyb_yl/zhuanjiasubpages/pages/bloodsugar_report/bloodsugar_report?j_id=' + that.data.j_id,
														})
													} else if (that.data.type == 'UA') {
														wx.navigateTo({
															url: '/hyb_yl/pharmacy/pages/uric_acid/uric_acid?j_id=' + that.data.j_id,
														})
													} else if (that.data.type == 'CHOL') {
														wx.navigateTo({
															url: '/hyb_yl/pharmacy/pages/cholesterol/cholesterol?j_id=' + that.data.j_id,
														})
													}

												}
											})
										}
									})

								}

							}
						}

					})
				}
			},
			fail: function (res) {
				console.log(res)
			}
		})

	},
	bindInput(e) {
		this.setData({
			inputText: e.detail.value
		})
		console.log(e.detail.value)
	},
	//	发包数据处理
	SendData(threeArr) {
		//		let threeArr='00';//第三位数字
		//		获取日期
		let getT = new Date();
		let Ty = '', Tm = '', Td = '', Th = '', Tmi = '', Ts = '', Tdate = '', Tadd = '';
		Ty = getT.getFullYear() % 1000;
		Tm = getT.getMonth() + 1;
		Td = getT.getDate();
		Th = getT.getHours();
		Tmi = getT.getMinutes();
		Ts = getT.getSeconds();
		Tdate = Ty + '-' + Tm + '-' + Td + ' ' + Th + ':' + Tmi + ':' + Ts;
		//		获取包的最后一位数字
		Tadd = 90 + 10 + Number(threeArr) + Ty + Tm + Td + Th + Tmi + Ts + 2;
		if (Tadd > 255) {
			//			获取最后两位
			Tadd = (Tadd % 255);
		}
		//		转十六进制
		threeArr = '0x' + threeArr.toString(16);
		Ty = '0x' + Ty.toString(16);
		Tm = '0x' + Tm.toString(16);
		Td = '0x' + Td.toString(16);
		Th = '0x' + Th.toString(16);
		Tmi = '0x' + Tmi.toString(16);
		Ts = '0x' + Ts.toString(16);
		Tadd = '0x' + Tadd.toString(16);
		let sendArr = ['0x5A', '0x0A', threeArr, Ty, Tm, Td, Th, Tmi, Ts, Tadd];

		let val = new Uint8Array(sendArr);
		var receiveText = buf2hex(val.buffer)
		console.log(threeArr + '--数据：' + receiveText)
		if (threeArr == '0x00') {
			this.pakInfoFun('发送信息读取包00：', receiveText)
		} else if (threeArr == '0x03') {
			this.pakInfoFun('发送数据读取包03：', receiveText)
		}
		return sendArr;
	},
	//	发包
	Send(threeArr) {
		var that = this;
		if (that.data.connected) {
			//发包内容
			let val = new Uint8Array(that.SendData(threeArr));
			wx.writeBLECharacteristicValue({
				deviceId: that.data.connectedDeviceId,
				serviceId: that.data.serviceId,
				characteristicId: that.data.writeCharacteristicsId,
				value: val.buffer,
				success: function (res) {
					console.log('发包成功')
					console.log(res)
					that.pakInfoFun('发包成功：', threeArr)
				},
				fail: function (res) {
					console.log(res)
					console.log('发包失败')
					that.pakInfoFun('发包失败：', threeArr)
				},
				complete: function (res) {
					console.log('完成')
					console.log(res)

				}

			})
		} else {
			that.BlelinkFail();
		}
	},
	//处理得出的结果
	handleResult(data) {
		var testValue1 = data.substr(18, 2), testValue2 = data.substr(20, 2);
		var testValue3 = '0x' + testValue2 + testValue1;
		//保留1位小数
		testValue3 = parseInt(parseInt(testValue3) / 10) / 10;
		return testValue3
	},
})